package com.guch.help.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.widget.RadioGroup;

import com.guch.help.R;
import com.guch.help.fragment.HomeFragment;
import com.guch.help.fragment.OtherFragment;
import com.guch.help.fragment.UserFragment;

public class NavigationActivity extends AppCompatActivity {
    private RadioGroup ansRadioGroup;
    private Fragment mCurrFragment;
    private HomeFragment homeFragment;
    private UserFragment userFragment;
    private OtherFragment otherFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation);

        initView();
        selectPage(0);
    }

    private void initView(){
        ansRadioGroup = findViewById(R.id.ans_radio_group);
        ansRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                selectPage(ansRadioGroup.indexOfChild((ansRadioGroup.findViewById(checkedId))));
            }
        });
    }

    private void selectPage(int index){
        switch (index){
            case 0:
                if(homeFragment == null){
                    homeFragment = new HomeFragment();
                }
                changeFragment(homeFragment);
                break;
            case 1:
                if(userFragment == null){
                    userFragment = new UserFragment();
                }
                changeFragment(userFragment);
                break;
            case 2:
                if(otherFragment == null){
                    otherFragment = new OtherFragment();
                }
                changeFragment(otherFragment);
                break;
        }
    }

    private void changeFragment(Fragment showFragment){
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft =  fm.beginTransaction();
        if(!showFragment.isAdded()){
            ft.add(R.id.ant_frame_layout,showFragment);
        }
        if(mCurrFragment !=null){
            ft.hide(mCurrFragment);
        }
        mCurrFragment = showFragment;
        ft.show(mCurrFragment);
        ft.commit();
    }
}

